#include <iostream>
#include <cstring>
#include <unistd.h>
#include <netinet/in.h> // 包含sockaddr_in结构体和相关常量
#include <arpa/inet.h>  // 包含IP地址转换函数
#include "InetAddr.hpp"
#include "log.hpp"

using namespace LogModule;
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage: ./client ip port" << std::endl;
        exit(1);
    }

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);

    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    InetAddr server(ip, port);
    // 先存到左值变量
    auto addr = server.GetAddr();
    // 连接服务端：
    int n = connect(sockfd, (struct sockaddr *)&addr, sizeof(addr));

    if (n < 0)
    {
        LOG(LogLevel::ERROR) << "client connect fail!!";
        exit(2);
    }
    LOG(LogLevel::INFO) << "client connect success!!";
    while (1)
    {
        std::cout << "Please Enter:" << std::endl;
        std::string line;
        getline(std::cin, line);
        write(sockfd, line.c_str(), line.size());

        // 接受服务端发回来的消息：
        char buffer[1024];
        int n = read(sockfd, buffer, sizeof(buffer) - 1);
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "read fail!!";
            exit(3);
        }
        buffer[n] = '\0';
        std::cout << buffer << std::endl;
    }
    close(sockfd);
    return 0;
}